// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import 'babel-polyfill'
import Vue from 'vue'
import axios from 'axios'
import Toast from 'vue-toasted'
import Vodal from 'vodal'
import App from './App'
import router from './router'
import store from './store'
import * as filters from './filters'
import 'vodal/common.css'
import 'vodal/zoom.css'
import './css/public.css'
import '../static/lib/ueditor.config.js'
import '../static/lib/ueditor.all.js'
import '../static/lib/lang/zh-cn/zh-cn.js'

Vue.config.productionTip = false

// 配置axios
axios.defaults.transformRequest = [
  function(data) {
    let ret = ''
    for (let it in data) {
      if (Array.isArray(data[it])) {
        data[it].forEach(item => {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(item) + '&'
        })
      } else {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
    }
    return ret
  }
]
// 把axios放到全局中
Vue.prototype.$http = axios
// 配置toast
Vue.use(Toast, {
  position: 'top-center',
  duration: 2000
})
// 全局滤镜
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})
// 全局引入modal插件
Vue.component(Vodal.name, Vodal)
router.afterEach(() => {
  window.scrollTo(0, 0)
})
store.dispatch('getUserInfo').then(data => {
  if (data.data.httpCode === 200) {
    store.dispatch('getUserMenus', store.state.uesrRole).then(data => {
      initVue()
    }, err => {
      console.log(err)
    })
  } else {
    initVue()
    router.replace('/login')
  }
}, err => {
  initVue()
  router.replace('/login')
  console.log(err)
})
/* eslint-disable no-new */
function initVue() {
  new Vue({
    el: '#app',
    router,
    store,
    template: '<App/>',
    components: { App }
  })
}
